import { login } from '../../services/user'
import { getBannerDetail } from '../../services/home'
import { searchItems } from '../../services/goods'

Page({
  data: {
    goodsList: [],
    background: [],

    id: '',
    type: '',
    isEnd: true,
  },
  onShow() {
    my.setNavigationBar({
      title: '推荐商品',
      backgroundColor: '#4BA3F9'
    })
  },
  onLoad({ id, type, name='', data }) {
    if (id && type) {
      if (type == 'banner') {
        this.getBannerData(id, name)
      } else if (type == 'menu') { 
        // 搜索时 id对应商品type name对应关键字
        this.setData({isEnd: false})
        this.getSearchData()
      }

      this.setData({ id, type, name })
    } else if (data) {
      let data = JSON.parse(data)
      let background = []
      if (data.bannerImage) {
        background.push({ bannerImage: decodeURIComponent(data.bannerImage) })
      }
      this.setData({ background: background, goodsList: data.goodsList })
    }
  },
  getBannerData(id, name) {
    getBannerDetail({ type: id, name }).then(({ code, data, msg }) => {
      if (code != 0) {
        return false
      }

      const items = []
      const images = []

      data.cats.forEach(cat => {
        items.push(...cat.items)
        images.push({ bannerImage: cat.image})
      })

      this.setData({ goodsList: items, background: images })
    })
  },
  async getSearchData() {
    const { id: type, name, page } = this.data
    const { code, data } = await searchItems({ name, type, page_num: page })

    if (code != 0) return false;

    this.setData({ goodsList: data.list, page: page + 1, isEnd: data.list.length < 10 })
  },
  onListClick({ target: { dataset } }) {
    const { onClick } = this.data.navList[dataset.index];
    if (onClick) {
      onClick();
    }
  },

  entriesTap(event) {
    console.log(event)
    if (event.target.dataset.url) {
      my.navigateTo({
        url: event.target.dataset.url
      })
    }
  }
});
